﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ClientNodeGui
{
	public partial class ClientOptionsDialog : Form
	{
		public ClientOptionsDialog()
		{
			InitializeComponent();
			NodeName = String.Empty;
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			txtClientName.Text = NodeName;
			txtLongTimeout.Text = LongTimeout.ToString();
			txtShortTimeout.Text = ShortTimeout.ToString();
			txtServerAddress.Text = ServerAddress;
			checkServerConfig.Checked = AllowServerControl;

			this.Icon = CommonLib.CommonResources.CommonIcon;
		}

		public String NodeName;
		public int ShortTimeout;
		public int LongTimeout;
		public String ServerAddress;
		public bool AllowServerControl;

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			try
			{
				if (String.IsNullOrEmpty(txtClientName.Text))
					throw new ArgumentException("Client node name is empty");

				if (txtClientName.Text.Length > 30)
					throw new ArgumentException("Client node name is too long -- 30 char limit");

				NodeName = txtClientName.Text;

				int num = 0;
				int.TryParse(txtShortTimeout.Text, out num);
				if (num <= 0 || num > 240)
					throw new ArgumentException("Error comm timeout is not a valid value -- (1,240)");
				ShortTimeout = num;
				num = 0;
				int.TryParse(txtLongTimeout.Text, out num);
				if (num <= 0 || num > 240)
					throw new ArgumentException("Normal comm timeout is not a valid value -- (1,240)");
				LongTimeout = num;

				AllowServerControl = checkServerConfig.Checked;

				if (txtServerAddress.Text == null)
					txtServerAddress.Text = String.Empty;

				if (txtServerAddress.Text.StartsWith("net.tcp://") == false)
					txtServerAddress.Text = txtServerAddress.Text + "net.tcp://";
				if (Uri.IsWellFormedUriString(txtServerAddress.Text, UriKind.Absolute) == false)
				{
					throw new ArgumentException("The specified address is not a valid URI");
				}
				Uri u = new Uri(txtServerAddress.Text);
				ServerAddress = txtServerAddress.Text;

				this.DialogResult = DialogResult.OK;
				this.Close();
			}
			catch (ArgumentException ex)
			{
				lblErrorMsg.Text = "Error: " + ex.Message;
			}
		}
	}
}
